import { message } from "antd";
import moment from 'moment';
import { imgHostUrl, imgPrefix, miniPro } from "./constants";
// @ts-ignore
import PrintArea from './Print';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const showMsg = (msg: string, type?: string) => {
  if (type) {
    message[type](msg);
  } else {
    message.error(msg);
  }
}

export const MsgType = {
  SUCCESS: 'success',
  ERROR: 'error',
  INFO: 'info'
}

export const formatDate = (date: string, format?: string) => {
  return moment(date).format(format || 'YYYYMMDDHHmmss')
}

export const parseDate = (date: string) => {
  return moment(`${date.substring(0, 4)}-${date.substring(4, 6)}-${date.substring(6)}`)
}

export const parseDate2 = (date: string) => {
  return moment(date);
}

export const diffDays = (begin: string, end: string) => {
  return (moment(end).valueOf() - moment(begin).valueOf()) / (24 * 60 * 60 * 1000)
}

export const subtractDays = (days) => {
  return moment().subtract(days, 'day');
}

export const currentDate = () => {
  return moment();
}

// 打印
export const print = (dom, options = {}) => {
  const printArea = new PrintArea(dom, { ...options });
  printArea.print();
}

// 去所有空格
export const trim = (str1: any) => {
  const str = str1 === undefined ? '' : `${str1}`;
  return str.replace(/\s/g, '');
}

// 判断是否为空
export const isNull = (value: any) => {
  let values = `${value}`;
  values = trim(value);
  if (values === '' || values === '""' || values === 'undefined' || values === undefined || values === null || values === 'null') {
    return true;
  }
  return false;
}
// 判断数组中是否包含某个字符串
export const inArray = (arr: Array<any>, item: String, type = 'bol', arrKey?: any) => {// eslint-disable-line
  for (let i = 0; i < (arr || []).length; i += 1) {
    if (isNull(arrKey) ? arr[i] === item : arr[i][arrKey] === item) {
      return type === 'bol' ? true : i;
    }
  }
  return type === 'bol' ? false : -1;
}

export const setCache = (key, value) => {
  localStorage.setItem(key, value);
}

export const getCache = (key) => {
  return localStorage.getItem(key);
}

export const formatMoney = (value: number | string, hidePrefix?: boolean) => {
  return value && `${!hidePrefix ? '¥ ' : ''}${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

export const getDateValue = (date) => {
  return moment(date).valueOf();
}
// 获取商城、店铺启用模块
export const getTag = (tag_id: string) => {
  switch (tag_id) {
    case '10001': return 'blue';
    case '10002': return 'cyan';
    case '10003': return 'red';
    case '10004': return 'green';
    case '10005': return 'orange';
    default:
      return '';
  }
}

// 视频格式
export const videoType = new Array("avi", "wmv", "mpg", "mpeg", "mov", "rm", "ram", "swf", "flv", "mp4", "mp3", "wma", "avi", "rm", "rmvb", "flv", "mpg", "mkv");

// 获取文件后缀
export const getFileExtension = (fileName: string) => {
  return fileName && fileName.substring(fileName.lastIndexOf('.') + 1);
}
// 合并行 list:数组,key：要合并的字段，value:要显示的值，record:当前行数据,index：当前下标
export const hbSpan = (list, key, value, record, index) => {
  const obj = {
    children: value,
    props: {},
  };
  const arr = list.filter((res) => {
    //这里key是我需要判断的字段名（相同就合并）
    return res[key] === record[key];
  });
  // console.log('list.length', list.length, index)
  // key相同的时候合并行
  if (!isNull(list) && (index === 0 || (list[index - 1][key] !== record[key]))) {
    obj.props.rowSpan = arr.length;
  } else {
    obj.props.rowSpan = 0;
  }
  return obj;
}
// 按钮是否有权限
export const isExits = (actid: string) => {
  const buttonIdList = JSON.parse(localStorage.getItem('buttonIdList')) || [];
  return !isNull(buttonIdList.find(e => e === actid));
}
// 判断是否支持sticky，用途：医院浏览器版本不支持固定列，因此有此方法
export const isSupportSticky = () => {
  const prefixTestList = ['', '-webkit-'];
  let stickyText = '';
  for (let i = 0; i < prefixTestList.length; i++) {
    stickyText += 'position:' + prefixTestList[i] + 'sticky;';
  }
  // 创建一个dom来检查
  let div = document.createElement('div');
  div.style.cssText = stickyText;
  document.body.appendChild(div);
  const isSupport = /sticky/i.test(window.getComputedStyle(div).position);
  document.body.removeChild(div);
  div = null;
  return isSupport;
}
// 搜索住院号/病案号，此方法用于判断最终传给接口的字段名称。 input_no：输入的值，canAll：是否不限制（科室/是否出院）查询，fromTo：引用的页面标识
export const searchKey = (input_no, canAll, fromTo) => {
  // 就诊卡
  if (input_no.length > 10 && input_no.length < 15) {
    return 'ic_card_no';
  }
  // 出院办结页
  if (fromTo === 'discharged') {
    return input_no.includes('R') ? 'out_visit_no' : 'out_case_no';
  }
  // 住院号
  if (input_no.includes('R')) {
    return canAll ? 'out_visit_no' : 'visit_no';
  }
  // 病案号
  return canAll ? 'out_case_no' : 'case_no';
}
// 表格是否需要横向滚动条
export const isScroll = window.innerWidth < 1400;

// 获得在职状态
export const getjobStatus = {
  Y: '在职',
  N: '离职',
  W: '待岗',
};

export const replaceImgHost = (imgUrl = '') => {
  if (imgUrl.indexOf(imgPrefix) > -1) {
    return imgUrl.replace(imgPrefix, imgHostUrl);
  }
  if (imgUrl.indexOf(miniPro) > -1) {
    return imgUrl.replace(miniPro, imgHostUrl);
  }
  if (imgUrl.indexOf('https://life.cdsrmyy.com/') > -1) {
    return imgUrl.replace('https://life.cdsrmyy.com/', imgHostUrl);
  }
  if (imgUrl.indexOf('http://sbutterfly.med.gzhc365.com/') > -1) {
    return imgUrl.replace('http://sbutterfly.med.gzhc365.com/', imgHostUrl);
  }
  return imgUrl
}

export const replaceRichTextImgHost = (content = '') => {
  content = `${content}`;
  content = content.replace(/http(s)?:\/\/sksptapp.med.gzhc365.com\//gm, imgHostUrl);
  content = content.replace(/http(s)?:\/\/sbutterfly.med.gzhc365.com\//gm, imgHostUrl);
  content = content.replace(/http(s)?:\/\/life.cdsrmyy.com\//gm, imgHostUrl);
  return content;
}

export const submitRichTextImgHost = (content = '') => {
  content = `${content}`;
  content = content.replace(/http(s)?:\/\/10.105.2.17:60001\//gm, miniPro);
  content = content.replace(/http(s)?:\/\/sksptapp.med.gzhc365.com\//gm, miniPro);
  content = content.replace(/http(s)?:\/\/sbutterfly.med.gzhc365.com\//gm, miniPro);
  content = content.replace(/http(s)?:\/\/life.cdsrmyy.com\//gm, miniPro);
  return content;
}

/** 判空 */
export function notNull(value: any) {
  if (value == undefined || value == null) {
    return false;
  }
  return true;
}

/** 判断空数组、空对象、空字符串 */
export function notEmpty(value: any) {
  if (!notNull(value))
    return false;
  if (Array.isArray(value) && value.length === 0) {
    return false;
  }
  if (value instanceof String && value.trim() === '') {
    return false;
  }
  if (value instanceof Object && Object.keys(value).length === 0) {
    return false;
  }
  return true;
}

// 设置打印样式
export function setPageSize(cssPageSize: string = 'portrait') {
  const style = document.createElement('style');
  style.innerHTML = `@page {size: ${cssPageSize}}`;
  style.id = 'page-orientation';
  document.head.appendChild(style);
}

// 设置身份证样式（因为有的数据是已经脱敏的，正则写有问题（也不太会改正则），就没用正则）
export function maskedIdCard(idCard: string = '') {
  // const reg1 = /^(.{3})(?:\d+)(?:)(.{3})$/;
  // return idCard.replace(reg1, '\$1**********\$2')
  const len = idCard.length;
  let start = '';   
  for (let i = 0;i < len - 6; i++) {
    start += '*';
  }
  // 最后的返回值由三部分组成
  return idCard.substring(0,3)+start+idCard.substring(idCard.length-3);
}